/**使用示例
<template>
  <div v-waterMarker="{text:'xxx版权所有',textColor:'rgba(180, 180, 180, 0.5)'}"></div>
</template>
 */

import Vue from 'vue';

function addWaterMarker(parentNode, str = '我是水印', font, textColor) {
    // 父元素，水印文字，字体，文字颜色
    let can = document.createElement('canvas');
    parentNode.appendChild(can);
    can.width = 200;
    can.height = 150;
    can.style.display = 'none';
    let cans = can.getContext('2d');
    cans.rotate((-20 * Math.PI) / 180);
    cans.font = font || '16px Microsoft JhengHei';
    cans.fillStyle = textColor || 'rgba(180, 180, 180, 0.4)';
    cans.textAlign = 'left';
    cans.textBaseline = 'Middle';
    cans.fillText(str, can.width / 10, can.height / 2);
    parentNode.style.backgroundImage = 'url(' + can.toDataURL('image/png') + ')';
}

const waterMarker = Vue.directive('waterMarker', {
    inserted: function (el, binding) {
        if (binding.value) {
            addWaterMarker(el, binding.value.text, binding.value.font, binding.value.textColor);
        } else {
            addWaterMarker(el);
        }
    },
});

export { waterMarker };
